﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Willow.Authorization;
using Willow.MVC.Result;
using Willow.Const;
using System.Net;
using Willow.IService.Auth;
using Willow.Common;
namespace Willow.WebApplication.Controllers
{
    public class HomeController : Controller
    {

        #region 属性

        public IUserService UserService { get; set; }

        #endregion

        #region 页面

        /// <summary>
        /// 注销跳转登陆页
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            OnlineContext.Instance.Logout();
            return RedirectToAction("Login");
        }

        /// <summary>
        /// 跳转到登陆页
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ViewResult RedirectToLogin()
        {
            return View();
        }

        /// <summary>
        /// 系统首页
        /// </summary>
        /// <returns></returns>
        public ViewResult Index()
        {
            string ip = NetHelper.GetRequestIP();
            ViewBag.FooterLeftMessage = "IP:" + ip;
            ViewBag.FooterCenterMessage = " Copyright © Mark 版权所有";
            ViewBag.FooterRightMessage = DateTime.Now.ToString("yyyy年MM月dd dddd ");
            //return View("MenuIndex");
            return View();
        }

        /// <summary>
        /// 登陆页
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ViewResult Login()
        {
            return View();
        }

        /// <summary>
        /// 生成左侧菜单Html
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        public ViewResult RenderTreeNavigate()
        {
            StringBuilder menuBuilder = new StringBuilder();

            var modules = OnlineContext.Instance.GetCurrentUser().LoginModules.OrderBy(p => p.DisplayOrder);
            //循环生成伸缩菜单
            menuBuilder.Append(string.Format("<div id=\"{0}\" class=\"easyui-accordion\" data-options=\"fit:true,border:false,animate:true\">", "navigate"));
            var rootModules = modules.Where(i => i.ParentId == DataBaseConst.DefaultParentId);
            foreach (var root in rootModules)
            {
                menuBuilder.Append(string.Format("<div title=\"{0}\" iconCls=\"{1}\" style=\"overflow: auto;\">", root.Name, root.Icon));
                GenerateSubTree(root.Id, modules, menuBuilder);
                menuBuilder.Append("</div>");
            }

            menuBuilder.Append("</div>");
            ViewBag.NavigateHtml = menuBuilder.ToString();
            return View();
        }

        /// <summary>
        /// 生成菜单式导航
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        public ViewResult RenderMenuNavigate()
        {
            StringBuilder menuBuilder = new StringBuilder();

            var modules = OnlineContext.Instance.GetCurrentUser().LoginModules.OrderBy(p => p.DisplayOrder);
            //循环生成菜单
            var rootModules = modules.Where(i => i.ParentId == DataBaseConst.DefaultParentId);
            foreach (var root in rootModules)
            {
                StringBuilder submenuBuilder = new StringBuilder();
                bool hasSubMenu = GenerateSubMenu(root.Id, modules, submenuBuilder);
                if (hasSubMenu)
                {
                    //包含子菜单，生成splitbutton按钮
                    menuBuilder.Append(string.Format("<a href=\"#\" class=\"easyui-splitbutton\" data-options=\"menu:'#{0}',iconCls:'{1}'\">{2}</a>", root.Id, root.Icon, root.Name));
                    menuBuilder.Append(string.Format("<div id=\"{0}\" style=\"width:150px;\">", root.Id));
                    menuBuilder.Append(submenuBuilder);
                    menuBuilder.Append("</div>");
                }
                else
                {
                    //不包含子菜单，生成linkbutton按钮
                    menuBuilder.Append(string.Format("<a href=\"#\" class=\"easyui-linkbutton willow-menu\" data-options=\"url:'{0}',plain:true,iconCls:'{1}'\">{2}</a>", root.URL, root.Icon, root.Name));
                }

            }
            ViewBag.NavigateHtml = menuBuilder.ToString();
            return View();
        }

        #endregion

        #region 操作

        /// <summary>
        /// 保持在线
        /// </summary>
        /// <returns></returns>
        public JsonResult KeepAlive()
        {
            return Json(DateTime.Now, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPassword">The old password.</param>
        /// <param name="newPassword">The new password.</param>
        /// <returns></returns>
        public JsonResult ChangePassword(string oldPassword, string newPassword)
        {
            var currUserId = OnlineContext.Instance.GetCurrentUser().UserId;
            return this.StandardJson(() =>
            {
                UserService.ChangePassword(currUserId, oldPassword, newPassword);
            });
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public JsonResult Login(string username, string password)
        {
            return this.StandardJson(() =>
            {
                UserService.Login(username, password);
            });
        }

        /// <summary>
        /// 生成树形子菜单Html
        /// </summary>
        /// <param name="ParentID">The parent identifier.</param>
        /// <param name="modules">The modules.</param>
        /// <param name="menuBuilder">The menu builder.</param>
        private static void GenerateSubTree(Guid ParentID, IEnumerable<LoginModule> modules, StringBuilder menuBuilder)
        {
            var subModules = modules.Where(p => p.ParentId == ParentID);

            if (subModules.Count() == 0)
            {
                return;
            }

            menuBuilder.Append("<ul class=\"easyui-tree\">");
            foreach (var item in subModules)
            {
                menuBuilder.Append("<li iconCls=\"" + item.Icon + "\"><span>" + item.Name + "<input type=\"hidden\" value=\"{url:'" + item.URL + "',iconCls:'" + item.Icon + "'}\"></span>");
                GenerateSubTree(item.Id, modules, menuBuilder);
                menuBuilder.Append("</li>");

            }
            menuBuilder.Append("</ul>");
        }

        /// <summary>
        /// 生成横向菜单Html
        /// </summary>
        /// <param name="ParentID">The parent identifier.</param>
        /// <param name="modules">The modules.</param>
        /// <param name="menuBuilder">The menu builder.</param>
        private static bool GenerateSubMenu(Guid ParentID, IEnumerable<LoginModule> modules, StringBuilder menuBuilder)
        {
            var subModules = modules.Where(p => p.ParentId == ParentID);

            if (subModules.Count() == 0)
            {
                return false;
            }

            foreach (var item in subModules)
            {
                menuBuilder.Append("<div style=\"width:150px;\" data-options=\"iconCls:'" + item.Icon + "',url:'" + item.URL + "'\" class=\"willow-menu\" >" + item.Name);
                GenerateSubMenu(item.Id, modules, menuBuilder);
                menuBuilder.Append("</div>");
            }
            return true;
        }

        #endregion
    }
}